package cn.itcast.nio.c4;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.atomic.AtomicInteger;

import static cn.itcast.nio.c1.ByteBufferUtil.debugAll;

/**
 * @Author: LDeng
 * @Date: 2021-05-14 10:17
 */
@Slf4j
public class MultiThreadServer {

    public static void main(String[] args) throws IOException {
        Thread.currentThread().setName("Thread0-boss");
        ServerSocketChannel ssc = ServerSocketChannel.open();
        ssc.configureBlocking(false);
        Selector bossSelector = Selector.open();
        SelectionKey bossSelectionKey = ssc.register(bossSelector, SelectionKey.OP_ACCEPT, null);
        ssc.bind(new InetSocketAddress(8080));
        Worker worker = new Worker("worker-0");
        Worker[] workers = new Worker[Runtime.getRuntime().availableProcessors()];
        for (int i = 0; i < workers.length; i++) {
            workers[i] = new Worker("worker-" + i);
        }
        AtomicInteger index = new AtomicInteger();
        while (true) {
            bossSelector.select();
            Iterator<SelectionKey> iterator = bossSelector.selectedKeys().iterator();
            while (iterator.hasNext()) {
                SelectionKey key = iterator.next();
                if (key.isAcceptable()) {
                    SocketChannel sc = ssc.accept();
                    sc.configureBlocking(false);
                    log.debug("{}  connected...", sc.getRemoteAddress());
                    log.debug("before register...READ {}", sc.getRemoteAddress());
                    //模数组长度并自增，轮询
                    workers[index.getAndIncrement() % workers.length].initWorker(sc);
                    log.debug("after register...READ {}", sc.getRemoteAddress());

                }
            }


        }

    }

    static class Worker implements Runnable {
        private Thread thread;
        private Selector workerSelector;
        private String name;
        private volatile boolean start = false;

        private ConcurrentLinkedQueue<Runnable> queue = new ConcurrentLinkedQueue<>();

        public Worker(String name) {
            this.name = name;
        }

        //初始化线程和selector
        public void initWorker(SocketChannel sc) throws IOException {
            if (!start) {
                workerSelector = Selector.open();
                thread = new Thread(this, "Thread1-" + name);
                thread.start();
                start = true;
                log.debug("worker inited..." + thread.getName() + "线程被创建，");
            }
            log.debug("=====>创建任务并加入到queue");
            queue.add(() -> {
                try {
                    sc.register(workerSelector, SelectionKey.OP_READ, null);
                    log.debug("sc       的register()方法 是被：" + Thread.currentThread().getName() + " 执行的！");
                } catch (ClosedChannelException e) {
                    e.printStackTrace();
                }
            });
            log.debug("=====>唤醒workSelector");
            workerSelector.wakeup();//唤醒workSelector
        }

        @Override
        public void run() {
            while (true) {
                try {
                    workerSelector.select();//worker-0线程
                    log.debug("workerSelect的select() 方法 是被：" + Thread.currentThread().getName() + " 执行的！");
                    Runnable task = queue.poll();
                    if (task != null) {
                        log.debug("取出queue中的任务并执行");
                        task.run();//等价执行了 sc.register(workerSelector,SelectionKey.OP_READ,null);
                    }
                    Iterator<SelectionKey> iterator = workerSelector.selectedKeys().iterator();
                    while (iterator.hasNext()) {
                        SelectionKey key = iterator.next();
                        iterator.remove();
                        if (key.isReadable()) {
                            ByteBuffer buffer = ByteBuffer.allocate(16);
                            SocketChannel sc = (SocketChannel) key.channel();
                            log.debug("read data from client...", sc.getRemoteAddress());
                            sc.read(buffer);
                            buffer.flip();
                            debugAll(buffer);
                        }
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }


        }
    }


}
